package com.zerowidth.moc.web.pay.hl;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.zerowidth.moc.web.utils.GsonUtils;
import com.zerowidth.moc.web.utils.IOUtil;
import com.zerowidth.moc.web.utils.LogUtil;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.TimeUnit;

public class HLPayOrderFactory {

    private static final String TAG = "HLPayOrderFactory";

    private static final String URL = "https://api.hbhlpay.com";

    private static String MY_SERVER_IP = "116.62.121.194";

    private static String ins_id = "M138767038";
    private static String app_id = "APP_849847556341";
    private static String CHARSET = "utf-8";
    private static String SIGN_TYPE = "RSA2";

    private static final String MY_PRIVATE_KEY = "MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQDC357iFbHHf/y1NGYKuJLS/wCfEMOMrtZa55hLiViPa2U63nJeRND145OczE9PezZ2ESsB+N3IMq0yN7rDNo2sLXvqkbe760V/woMaS/FFGv+nV3CSLiio5vOUpnHtSqzAQ1Cf8AcuGSAQCPzjWvVl3IpKczPOU+qbB2cCXo1Y4+DES5rPTxeI3c035D+DS8oXL3yMSAq8O4IMdt/3Ecc4O89YRAHc7hNXqxoAeJUccVW9TAO02xAxYEKJa9CsOHDSjs1q6/m90euBLhC9Th1GUTGW19pG/cMmqHkg+AGmra4x1iBAoPkVwNMMtVenxTC1gmBZvfoDIDSA0//+OxlHAgMBAAECggEBALu+/jALfrAaGrnptbX2hV5K16poWD4d497I6e08cdobOfgxgDZaTofXrcuO+4ozxxCREcJgpivOxxZuoryYvn13hL9FjKK71MV1/SFEsTpG/K+YipgLaJjxiRNaGMDpBO5m7DJq6j/7bOyF/D5+z5ZHl+SKgQrzxj9+LjwWJE/R6mE5Kg1V4V2egrI0qptmB1mRRcXVzuwxNEwvH23hNOaPkb7NBpbfIuItpHUZo9vlzq4cY3qw+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lYj2tlOt5yXkTQ9eOTnMxPT3s2dhErAfjdyDKtMje6wzaNrC176pG3u+tFf8KDGkvxRRr/p1dwki4oqObzlKZx7UqswENQn/AHLhkgEAj841r1ZdyKSnMzzlPqmwdnAl6NWOPgxEuaz08XiN3NN+Q/g0vKFy98jEgKvDuCDHbf9xHHODvPWEQB3O4TV6saAHiVHHFVvUwDtNsQMWBCiWvQrDhw0o7Nauv5vdHrgS4QvU4dRlExltfaRv3DJqh5IPgBpq2uMdYgQKD5FcDTDLVXp8UwtYJgWb36AyA0gNP//jsZRwIDAQAB";
    private static final String HL_PUBLIC_KEY2 = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA3ZkSKmIdaFpKPekJmTjeaXbMAoXVAvG2b91S/jnDOirKwJO3iDPCdA9w1uiBYjnNjGYJdKRFNltKrex0GG7yvB3JUO1Htq0ifGCnNllQXIYb8j9om/xRqbDGU/DDCime98CkqIyet4N5zeSa3t5+aUJQp+X9XzoI4vSX0uWLmkNVOySm9he5ZX0STvFITl5gfN6A4dvH5paL/Sc3FFkB9rDqzN3DTdqJ4FC9WIbHXGFr8w/e/dtTMBhlZrt/NuPCbcoR4A3IwJkr/XUjSlTPmpyS8Vgg/Hgu7ZWY1nokbItkHhX1hWToYpnHsfEKPZjtq9hdeHViHxfjD8ZW9BqdDwIDAQAB";


    public static HLCreateOrderBean createOrderInfo2(int payType, String subject, String outTradeNo,
                                                     String notifyUrl, String amount) {

        String timeStamp = String.valueOf(System.currentTimeMillis() / 1000);
        FormBody.Builder form = new FormBody.Builder();
        form.add("ins_id", ins_id);
        form.add("app_id", app_id);
        form.add("sign_type", SIGN_TYPE);
        form.add("timestamp", timeStamp);

        JSONObject jsonObject = new JSONObject();

        if (payType == 0) {
            //微信支付
            jsonObject.put("sp_sn", "S175690380"); //用青回网络公司

            jsonObject.put("mch_channel_id", "143"); //通道ID=143，用青回网络公司

            jsonObject.put("way_code", "offWechatLiteH5");
        } else if (payType == 1) {
            //支付宝
            jsonObject.put("sp_sn", "S961833526"); //用零宽网络公司

            jsonObject.put("mch_channel_id", "142"); //通道ID=142，用零宽网络公司

            jsonObject.put("way_code", "offAlipayLiteH5");
        }

        jsonObject.put("mch_order_no", outTradeNo);
        jsonObject.put("amount", amount);
        jsonObject.put("client_ip", MY_SERVER_IP);
        jsonObject.put("subject", subject);
        jsonObject.put("notify_url", notifyUrl);

        form.add("biz_content", jsonObject.toJSONString());

        {
            TreeMap<String, String> treeMap = new TreeMap<>();
            treeMap.put("ins_id", ins_id);
            treeMap.put("app_id", app_id);
            treeMap.put("sign_type", SIGN_TYPE);
            treeMap.put("timestamp", timeStamp);
            treeMap.put("biz_content", jsonObject.toJSONString());

            try {
                String signStr = AlipaySignature.sign(treeMap, MY_PRIVATE_KEY, CHARSET, SIGN_TYPE);
                form.add("sign", signStr);

                LogUtil.e(TAG, "signStr = " + signStr);

            } catch (AlipayApiException e) {
                LogUtil.e(TAG, "e = " + e.getMessage());
            }

        }

        FormBody formBody = form.build();

        Request request = new Request.Builder()
                .url(URL + "/payment.order/create")
                .post(formBody)
                .build();
        Response response = null;

        try {
            response = getOkHttpClient().newCall(request).execute();

            String back = response.body().string();

            LogUtil.e(TAG, back);

            HLCreateOrderBean bean = GsonUtils.fromJsonStr(back, HLCreateOrderBean.class);

            LogUtil.e(TAG, "pay_info = " + bean.data.pay_info);

            return bean;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            IOUtil.close(response);
        }

        return null;
    }

    public static HLOrderInfoBean queryOrderInfo(String outTradeNo) {

        String timeStamp = String.valueOf(System.currentTimeMillis() / 1000);
        FormBody.Builder form = new FormBody.Builder();
        form.add("ins_id", ins_id);
        form.add("app_id", app_id);
        form.add("sign_type", SIGN_TYPE);
        form.add("timestamp", timeStamp);

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("mch_order_no", outTradeNo);

        form.add("biz_content", jsonObject.toJSONString());

        {
            TreeMap<String, String> treeMap = new TreeMap<>();
            treeMap.put("ins_id", ins_id);
            treeMap.put("app_id", app_id);
            treeMap.put("sign_type", SIGN_TYPE);
            treeMap.put("timestamp", timeStamp);
            treeMap.put("biz_content", jsonObject.toJSONString());

            try {
                String signStr = AlipaySignature.sign(treeMap, MY_PRIVATE_KEY, CHARSET, SIGN_TYPE);
                form.add("sign", signStr);

                LogUtil.e(TAG, "signStr = " + signStr);

            } catch (AlipayApiException e) {
                LogUtil.e(TAG, "e = " + e.getMessage());
            }

        }

        FormBody formBody = form.build();

        Request request = new Request.Builder()
                .url(URL + "/payment.order/query")
                .post(formBody)
                .build();
        Response response = null;

        try {
            response = getOkHttpClient().newCall(request).execute();

            String back = response.body().string();

            LogUtil.e(TAG, back);

            HLOrderInfoBean bean = GsonUtils.fromJsonStr(back, HLOrderInfoBean.class);

            LogUtil.e(TAG, "pay_info = " + bean.data.state);

            return bean;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            IOUtil.close(response);
        }

        return null;
    }

    private static OkHttpClient getOkHttpClient() {
        OkHttpClient.Builder okHttpClientBuilder = new OkHttpClient.Builder();

        long timeOut = 20_000;

        okHttpClientBuilder.callTimeout(timeOut, TimeUnit.MILLISECONDS);
        okHttpClientBuilder.connectTimeout(timeOut, TimeUnit.MILLISECONDS);
        okHttpClientBuilder.writeTimeout(timeOut, TimeUnit.MILLISECONDS);
        okHttpClientBuilder.readTimeout(timeOut, TimeUnit.MILLISECONDS);

        return okHttpClientBuilder.build();
    }

    public static boolean rsaCheck(Map<String, String> params) {
        try {
            return PaySignature.verifyV2(params, HL_PUBLIC_KEY2, CHARSET, SIGN_TYPE);
        } catch (ApiException e) {
            return false;
        }
    }

}
